﻿using System;

using System.Collections.Generic;
using System.Text;

namespace Silvermoon.Animations
{
    public abstract class EasingFunctionBase : IEasingFunction
    {
        private delegate float GetValueDelegate(float normalitedTime);

        private EasingMode mode;

        public EasingFunctionBase()
            : base()
        {
            GetValue = EaseValue;
        }

        public EasingMode Mode
        {
            get { return mode; }
            set
            {
                if (mode != value)
                {
                    mode = value;
                    Prepare();
                }
            }
        }

        private GetValueDelegate GetValue;

        protected virtual void Prepare()
        {
            switch (Mode)
            {
                case EasingMode.EaseIn:
                    GetValue = EaseValue;
                    break;

                case EasingMode.EaseOut:
                    GetValue = GetValueOut;
                    break;

                case EasingMode.EaseInOut:
                    GetValue = GetValueInOut;
                    break;

                default: throw new NotImplementedException();
            }

        }

        private float GetValueOut(float normalizedTime)
        {
            float normalized = 1f - normalizedTime;
            return 1f - EaseValue(normalized);
        }

        private float GetValueInOut(float normalizedTime)
        {
            if (normalizedTime < 0.5f)
            {
                return EaseValue(normalizedTime * 2f) / 2f;
            }
            else
            {
                return 0.5f + GetValueOut(normalizedTime * 2f - 1f) / 2f;
            }
        }

        #region IEasingFunction Members

        public float Ease(float normalizedTime)
        {
            return GetValue(normalizedTime);
        }

        protected abstract float EaseValue(float normalizedTime);

        #endregion
    }
}
